﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using NHibernate;
using NHibernate.Linq;
using JaxaraRnD.Models.Objects;

namespace JaxaraRnD.Helpers.DataAccess
{
    public class Repository<T>: IRepository<T>
    {
        private readonly ISession _session;

        public Repository()
        {
            _session = NHibernateHelper.GetSession();
        }
        public IList<T> GetAll()
        {
            return _session.Query<T>().ToList();
        }
        

        public IList<T> GetList(Expression<Func<T, bool>> predicate)
        {
            return _session.Query<T>().Where(predicate).ToList();
        }

        public T SaveOrUpdate(T entity)
        {
            _session.SaveOrUpdate(entity);
            _session.Flush();

            return entity;
        }

        public T Get(int id)
        {
            return _session.Get<T>(id);
        }

        public T Get(Expression<Func<T, bool>> predicate)
        {
            return _session.Query<T>().Where(predicate).SingleOrDefault();
        }

        public void Delete(int id)
        {
            using (_session.BeginTransaction())
            {
                T entity = _session.Get<T>(id);
                _session.Delete(entity);
                _session.Transaction.Commit();
            }
        }
        /*SKP Custom Start*/
        public IList<Order> GetOrdersByStuffId(int id)
        {
            return _session.Query<Order>().Where(x=>x.Staff.Id==id).ToList();
        }
        public IList<Product> GetProductsByProductIds(int[] ids)
        {
            return _session.Query<Product>().Where(x=>ids.Contains(x.Id)).ToList();
        }
        public Staff GetStaffByStaffId(int id)
        {
            return _session.Get<Staff>(id);
        }
        public IList<Order> GetOrdersByOrderids(int[] ids)
        {
            return _session.Query<Order>().Where(x=>ids.Contains(x.Id)).ToList();
        }
        
        /*SKP Custom End*/
    }
}